package com.adan.content.service.impl;

import com.adan.base.execption.XcPlusException;
import com.adan.content.mapper.CourseTeacherMapper;
import com.adan.content.model.po.CourseTeacher;
import com.adan.content.service.CourseTeacherService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author adan
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {

    @Override
    public List<CourseTeacher> queryCourseTeachers(Long courseId) {
        LambdaQueryWrapper<CourseTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CourseTeacher::getCourseId, courseId);
        return this.list(lqw);
    }

    @Override
    @Transactional
    public CourseTeacher saveCourseTeacher(CourseTeacher courseTeacher) {
        Long id = courseTeacher.getId();
        if (id != null){
            // id不为null，修改教师
            boolean update = this.updateById(courseTeacher);
            if (!update){
                XcPlusException.cast("修改失败");
            }
            return this.getById(courseTeacher.getId());
        }
        // id为null，新增教师
        boolean save = this.save(courseTeacher);
        if (!save){
            XcPlusException.cast("新增失败");
        }
        return this.getById(courseTeacher.getId());
    }

    @Override
    public void deleteCourseTeacher(Long courseId, Long teacherId) {
        LambdaQueryWrapper<CourseTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CourseTeacher::getId, teacherId)
                .eq(CourseTeacher::getCourseId, courseId);
        boolean remove = this.remove(lqw);
        if (!remove){
            XcPlusException.cast("删除失败");
        }
    }
}
